/**
 * Created by sunzhijun on 2019/01/01.
 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {high, createPage, base, getUrlParam, toast, promptBox, getBusinessInfo} from 'nc-lightapp-front';
import {getAppPageConfig, handleHash, hrAjax as ajax} from 'src/hrpub/common/utils/utils';
// import do_print from '../../../../hrpub/common/utils/print';
import printPage from './functions/print';
import './index.less';

let tableid = 'trnstypelist';

const moduleId = "hihr6007";
const domainName = "hrhi";
let modifyDataArr = [];
let tableData = [];

const appcode = "60070540", pagecode = "60070540p", format = "YYYY-MM-DD";
const {NCTable, NCDatePicker, NCModal, NCButton} = base;

class MainPage extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.editTable(tableid);
        }
        this.config = getAppPageConfig();
        this.state = {
            isShowSealDataFlag: false,   //是否显示停用
            defaultData: '',    //默认第一行数据
            requireData: '' //请求的数据
        }
        props.createUIDom(this.config, (data) => {
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                pk_org: 'GLOBLE00000000000000',
                telName: data.template.name || ''
            });
            props.meta.setMeta(data && data.template ? data.template : {}, () => {
                this.fetchTableData();
            });
            props.button.setButtons(data && data.button ? data.button : {});
        });
        // this.print = this.print.bind(this);
    }

    componentWillMount() {
        //window.location.hash = '?page=201908241349';
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt})//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: moduleId, domainName: domainName, callback});
        this.businessInfo = getBusinessInfo() || {groupId: '0001A7100000000004U0', groupName: ''};
    }

    componentDidMount() {
        // 计算列表的高度
        let bodyH = this.refs.getContainerDom.offsetHeight;
        let headerH = this.refs.getHeaderDom.offsetHeight;
        this.setState({
            tableHeight: bodyH - headerH - 36
        })
    }


    //数据初始化
    fetchTableData(code, isShow) {
        this.props.button.setButtonDisabled(['add', 'edit', 'delete'], true);
        let data = {
            'pk_org': this.state.pk_org
        };
        if (!!code) {
            data.trnstypecode = code;
        }
        data.showSealDataFlag = this.state.isShowSealDataFlag;
        // if(code != 'custom_root'){
        ajax({
            url: '/nccloud/hrhi/trnstype/TrnsTypeQueryActionGlb.do',
            data: data,
            success: res => {
                if (res.success) {
                    let treeData = res.data.treeData;
                    let rowsData = [];
                    if (!!res.data.trnsTypeData) {
                        rowsData = res.data.trnsTypeData.trnstypelist.rows;
                        this.setState({
                            defaultData: rowsData[0],  //默认选择第一行数据
                            requireData: rowsData
                        });
                        let isEnable = rowsData[0].values.enablestate.value;
                        if (isEnable == 2) { //判断所选择的数据是否停用改变按钮状态
                            this.props.button.setButtonDisabled(['enable'], true);
                            this.props.button.setButtonDisabled(['disable'], false);
                        } else {
                            this.props.button.setButtonDisabled(['disable'], true);
                            this.props.button.setButtonDisabled(['enable'], false);
                        }
                        this.props.button.setButtonDisabled(['print', 'preview', 'output'], false);
                    } else {
                        rowsData = [];
                        this.setState({
                            defaultData: rowsData,  //默认选择第一行数据
                            requireData: rowsData
                        });
                        this.props.button.setButtonDisabled(['disable', 'print', 'preview', 'output'], true);
                    }
                    tableData = rowsData;
                    this.props.editTable.setTableData(tableid, {rows: rowsData || []});
                    if (!!code) {
                        this.changeBtnStatus(code);
                    } else {
                        this.customTree(treeData);
                    }
                    this.props.editTable.focusRowByIndex(tableid, 0);
                    modifyDataArr = [];
                    this.sureCancel();
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
        // }
    }

    //保存
    saveTableData() {
        let allTableData = this.props.editTable.getAllRows(tableid);
        let saveData = modifyDataArr.length > 0 ? modifyDataArr : allTableData;
        !!saveData.length && saveData.map((item, index) => {
            item.values.numberindex.value = parseInt(item.values.numberindex.value) - 1 + '';
        })
        // this.props.editTable.checkRequired(tableid,modifyDataArr);
        ajax({
            url: '/nccloud/hrhi/trnstype/SaveTrnstypeAction.do',    //code 关键字
            data: {
                "nodetype": "group_node",
                "savedata": saveData
            },
            success: res => {
                if (res.success) {
                    this.fetchTableData(this.state.type);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    //改变按钮状态
    changeBtnStatus(status) {
        if (status == this.state.json['hihr-000016'] || status == this.state.json['hihr-000017'] || status == this.state.json['hihr-000019']) { //Why?后端返回都是中文包括id,
            this.props.button.setButtonDisabled(['add', 'edit', 'delete'], false);
        } else if (status == this.state.json['hihr-000020']) {
            this.props.button.setButtonDisabled(['edit'], false);
        } else {
            this.props.button.setButtonDisabled(['add', 'edit', 'delete'], true);
        }
    }

    //自定义tree
    customTree(data) {
        let root = [{
            children: [],
            code: this.state.json['hihr-000015'],
            iconBox: {
                addIcon: true,
                delIcon: true,
                editIcon: true
            },
            id: null,
            isOrgStruSort: false,
            innercode: null,
            key: 'root',
            name: this.state.json['hihr-000015'],
            nodeData: {
                nodeValue: {}
            },
            pid: null,
            refname: this.state.json['hihr-000015'],
            // refpk: 'custom_root',
            refpk: this.state.json['hihr-000015'],
            title: this.state.json['hihr-000015']
        }];
        Array.prototype.push.apply(root[0].children, data);
        this.props.syncTree.setSyncTreeData('treeDataId', root);
        // this.props.syncTree.setTreeEdit(true);
    }

    //获取某一处修改的数据索引
    searchIndex(arr, id) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].rowid == id) {
                return i;
            }
        }
    }

    //编辑数据后重组
    checkedOrNot(a, b, c, d, e, f, g, h) {
        let index = this.searchIndex(modifyDataArr, g.rowid);
        if (index >= 0) {
            modifyDataArr.splice(index, g);
        } else {
            modifyDataArr.push(g);
        }
    }

    //点击table row事件
    onRowClickEvent(a, b, c, d) {
        let rowData = c;
        let isEnable = rowData.values.enablestate.value;
        if (isEnable == 2) { //判断所选择的数据是否停用改变按钮状态
            this.props.button.setButtonDisabled(['enable'], true);
            this.props.button.setButtonDisabled(['disable'], false);
        } else {
            this.props.button.setButtonDisabled(['disable'], true);
            this.props.button.setButtonDisabled(['enable'], false);
        }
        // this.setState({
        //     pk_trnstype : pk_trnstype
        // })
        this.setState({
            defaultData: rowData
        })
    }

    //选择tree节点
    onSelectTree(v) {
        this.setState({
            type: v
        });
        let selectType = this.state.type;
        this.fetchTableData(selectType);
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus() {
        var showMode = this.state.showMode
        this.props.button.setButtonsVisible({
            add: showMode === 'browse',
            edit: showMode === 'browse',
            refresh: showMode === 'browse',
            reset: showMode === 'browse',
            save: showMode === 'edit',
            cancel: showMode === 'edit',
            print: showMode === 'browse',
            enable: showMode === 'browse',
            disable: showMode === 'browse',
            filter: showMode === 'browse',
            delete: showMode === 'browse'
        })
    }


    // 更新界面状态
    updateShowMode(showMode) {
        var oldMode = this.state.showMode;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        if (oldMode === showMode) {
            return;
        }
        if ('edit' === showMode) {
            this.props.editTable.setStatus(tableid, 'edit');
            // this.props.editTable.setColEditableByKey(tableid, "table",false)
        } else {
            this.props.editTable.cancelEdit(tableid);
        }
    }

    //确认弹窗
    promptBoxModal(context, func, args) {
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn: true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick: () => {
                func(args)
            },   // 确定按钮点击调用函数,非必输
            // cancelBtnClick: functionCancel,  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop: false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }

    //确定取消
    sureCancel() {
        this.props.syncTree.setNodeDisable('treeDataId', false);
        this.updateShowMode('browse');
        modifyDataArr = [];
    }

    //显示停用
    showDisableData() {
        let ishow = this.state.isShowSealDataFlag;
        let type = this.state.type;
        this.setState({
            isShowSealDataFlag: !ishow
        }, () => {
            this.fetchTableData(type);
        });
    }

    //启用
    handdleEnable() {
        let defaultPkTrnstype = this.state.defaultData;
        let defaultValue = defaultPkTrnstype.values.pk_trnstype.value;
        let trnstype = defaultValue;
        ajax({
            url: '/nccloud/hrhi/trnstype/UseTrnstypeAction.do',
            data: {
                "nodetype": "globe_node",
                "pk_trnstype": trnstype
            },
            success: res => {
                if (res.success) {
                    this.fetchTableData(this.state.type);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    //停用
    handdleDisable() {
        let defaultPkTrnstype = this.state.defaultData;
        let defaultValue = defaultPkTrnstype.values.pk_trnstype.value;
        let trnstype = defaultValue;
        ajax({
            url: '/nccloud/hrhi/trnstype/UnuseTrnstypeAction.do',
            data: {
                "nodetype": "globe_node",
                "pk_trnstype": trnstype
            },
            success: res => {
                if (res.success) {
                    this.fetchTableData(this.state.type);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    // 新增一行
    addRow() {
        let len = this.state.requireData && this.state.requireData.length;
        ajax({
            url: '/nccloud/hrhi/trnstype/AddLineTrnstypeActionGlb.do',
            data: {
                nodetype: 'globe_node',
                trnsevent: this.state.type
            },
            success: res => {
                if (res.success) {
                    let defaultAlterData = res.data.trnstypelist.rows[0].values;
                    this.props.editTable.addRow(tableid, len, true, defaultAlterData);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    //获取选择行数据
    getCheckedRowsData() {
        return this.props.editTable.getCheckedRows(tableid);
    }

    //删除一行前验证
    deleteRowCheck() {
        let checkedDataArr = [];
        let checkedData = this.state.defaultData;
        checkedDataArr.push(checkedData);
        ajax({
            url: '/nccloud/hrhi/trnstype/BeforeDelTrnstryeGlbAction.do',
            data: {
                deldata: checkedDataArr
            },
            success: res => {
                if (res.success) {
                    if (res.data.flag) {
                        let deletePs = this.state.json['hihr-000021'];
                        this.promptBoxModal(deletePs, this.deleteRow.bind(this), checkedDataArr);
                    } else {
                        toast({color: "warning", content: res.data.resultmsg});
                    }
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    //删除
    deleteRow(checkedArr) {
        // let checkedData = this.getCheckedRowsData();
        ajax({
            url: '/nccloud/hrhi/trnstype/DelLineTrnstypeGlbAction.do',
            data: {
                "nodetype": "globe_node",
                deldata: checkedArr
            },
            success: res => {
                if (res.success) {
                    this.fetchTableData(this.state.type);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    // 打印
    print(tableid) {
        printPage.call(this, tableid);
    }


    // 统一处理按钮事件
    onBtnOperation(props, btncode, areacode, opt, recordRow, index) {
        let pk_id = '';
        let record = null;
        if (recordRow) {
            record = JSON.parse(JSON.stringify(recordRow));
            pk_id = record.values.pk_dataio_intface.value;
            this.setState({'row_id': pk_id})
        }
        switch (btncode) {
            case 'add':
                this.updateShowMode('edit');
                this.props.syncTree.setNodeDisable('treeDataId', true);
                this.addRow();
                break;
            case 'edit':
                this.updateShowMode('edit');
                this.props.syncTree.setNodeDisable('treeDataId', true);
                // this.props.form.setFormStatus(tableid, 'edit');
                // this.props.form.EmptyAllFormValue(tableid);
                // this.assignStepModal.show('assign', 'add', '');
                break;
            case 'reset':
                let lan1 = this.state.json['hihr-000001'];
                this.promptBoxModal(lan1, this.resetTableData.bind(this));
                break;
            case 'refresh':
                this.fetchTableData();
                break;
            case 'delete':
                this.deleteRowCheck();
                break;
            case 'enable':
                let lan3 = this.state.json['hihr-000014'];
                this.promptBoxModal(lan3, this.handdleEnable.bind(this));
                break;

            case 'disable':
                let lan4 = this.state.json['hihr-000011'];
                this.promptBoxModal(lan4, this.handdleDisable.bind(this));
                break;

            case 'save':
                this.saveTableData();
                break;
            case 'cancel':
                let lan2 = this.state.json['hihr-000002'];
                this.promptBoxModal(lan2, this.sureCancel.bind(this));
                break;
            case 'filter':

                break;
            case 'show':
                this.showDisableData();
                break;
            case 'print':
                this.print(tableid);
                break;
            case 'output':
                this.print(tableid);
                break;
            default:
                break;

        }

    }

    render() {
        let {button, search, DragWidthCom, modal, table, form, cardTable, editTable, cardPagination, syncTree} = this.props;
        const {createCardPagination} = cardPagination;
        let {createButtonApp} = button;
        let {NCCreateSearch} = search;
        let {createSimpleTable} = table;
        let {createModal} = modal;
        let {createForm} = form;
        let {createCardTable} = cardTable;
        let {createEditTable} = editTable;
        let {createSyncTree} = syncTree;//创建同步树 需要引入这个
        let {tableHeight} = this.state;
        return (
            <div className="nc-single-table" ref="getContainerDom">
                <div className="header" ref="getHeaderDom">
                    {/* 按钮区  btn-group */}
                    <div className="btn-group">
                        {createButtonApp({
                            area: 'head',//按钮注册中的按钮区域
                            buttonLimit: 1,
                            onButtonClick: (props, btncode) => this.onBtnOperation(props, btncode, 'list', this),
                            popContainer: document.querySelector('.btn-group')
                        })}
                    </div>
                </div>
                <div className="tree-card" style={{height: 'calc(100% - 46px)'}}>
                    <div className="dragWidthCom">
                        <div className="dragWidthCom_left" style={{width: "20%", minWidth: "50px"}}>
                            <div className="tree-area">
                                {createSyncTree({
                                    treeId: 'treeDataId',
                                    needEdit: false, //不启用编辑
                                    showLine: false, //显示连线
                                    needSearch: false, //是否需要搜索框
                                    onSelectEve: this.onSelectTree.bind(this),//选择
                                    // onMouseEnterEve:this.onMouseEnterEve.bind(this),
                                    // clickEditIconEve: this.onEditEps.bind(this), //编辑点击 回调
                                    // clickAddIconEve: this.onAddEps.bind(this), //新增点击 回调
                                    // clickDelIconEve: this.onDeleteEps.bind(this), // 删除点击 回调
                                    //userDefine: () =>{
                                    //    return (<NCIcon type="uf-correct"></NCIcon>)
                                    //},
                                    showModal: false
                                })}
                            </div>
                        </div>
                        <div class="dragWidthCom_line">
                            <div class="dragWidthCom_lines"></div>
                        </div>
                        <div className="dragWidthCom_right" id="tableListData">
                            {createEditTable(tableid, {
                                multipleRowCell: null,
                                showIndex: true,        //显示序列号
                                onAfterEvent: this.checkedOrNot.bind(this),             //表格状态监听
                                onRowClick: this.onRowClickEvent.bind(this),
                                // onBeforeEvent: this.onBeforeEvent.bind(this)
                                // showCheck: true
                                height: tableHeight
                            })}
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

const HomePage = handleHash('201908241349', 'c=60070540&p=60070540p')(createPage({})(MainPage));
ReactDOM.render(<HomePage/>, document.querySelector('#app'));
export default MainPage;
